package main

import (
	"bytes"
	"fmt"
	"gitee.com/ha666/golibs"
	"github.com/astaxie/beego/logs"
	"github.com/rpcx-ecosystem/rpcx-gateway"
	"github.com/smallnest/rpcx/codec"
	_ "ha666_http_client/initial"
	"io/ioutil"
	"log"
	"net/http"
	"rpc_models"
)

func main() {
	defer func() {
		if err := recover(); err != nil {
			logs.Error("【main】ex:%v", err)
			return
		}
	}()
	cc := &codec.MsgpackCodec{}
	args := &rpc_models.SystemGetTimeArgs{
		Base: rpc_models.BaseRequest{
			Ver:    180201,
			AppKey: 2018020116,
			Time:   golibs.Unix(),
			V:      1,
			Sign:   fmt.Sprintf("%x", golibs.Sha1([]byte(`fmt.Println(dog.name + " eat")`))),
		},
	}
	data, err := cc.Encode(args)
	if err != nil {
		log.Fatal("serialization error: ", err)
		return
	}
	req, err := http.NewRequest("POST", "http://127.0.0.1:9999/", bytes.NewReader(data))
	if err != nil {
		log.Fatal("failed to create request: ", err)
		return
	}

	h := req.Header
	h.Set(gateway.XMessageID, "10000")
	h.Set(gateway.XMessageType, "0")
	h.Set(gateway.XSerializeType, "3")
	h.Set(gateway.XServicePath, "BaseRPC")
	h.Set(gateway.XServiceMethod, rpc_models.System_GetTime)

	res, err := http.DefaultClient.Do(req)
	if err != nil {
		log.Fatal("failed to call: ", err)
	}
	defer res.Body.Close()

	// handle http response
	replyData, err := ioutil.ReadAll(res.Body)
	if err != nil {
		log.Fatal("failed to read response: ", err)
	}

	reply := &rpc_models.SystemGetTimeReply{}
	err = cc.Decode(replyData, reply)
	if err != nil {
		log.Fatal("failed to decode reply: ", err)
	}
	log.Println("IsSuccess:", reply.IsSuccess)
	log.Println("Code:", reply.Code)
	log.Println("Msg:", reply.Msg)
	log.Println("CurrentTime:", reply.CurrentTime)
	log.Println("CurrentTime:", reply.CurrentTime.Format(golibs.Time_TIMEStandard))
}
